package yanjunwei.rbac.util;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class SingletonFactory {

   private static final Map <Class<?>, Object>instanceMap=new ConcurrentHashMap<>();

   public static <T> T  getInstance(Class<T> clazz){
       if (clazz==null){
           throw new IllegalArgumentException("未知的类型");
       }
       if (!instanceMap.containsKey(clazz)){
           try {
               Constructor<T> constructor = clazz.getDeclaredConstructor();
               constructor.setAccessible(true);
             T singleton = constructor.newInstance();
               instanceMap.put(clazz, singleton);
           }catch (Exception e){
               throw new IllegalArgumentException("创建单例模式失败："+clazz.getSimpleName(),e);
           }
       }
       @SuppressWarnings("unchecked")
       T instance=(T)instanceMap.get(clazz);
       return instance;
   }

}
